﻿using EasyToHelp.Common;
using EasyToHelp.DBFactory;
using EasyToHelp.Entity;
using System;
using System.Collections.Generic;
using System.Text;

namespace EasyToHelp.Service
{
    public class ShopService: IShopService
    {
        public int Edit(ShopLeaseInfo model)
        {
            using (var db = ContextHelper.Context(ContextHelper._connString))
            {
                db.Session.BeginTransaction();
                try
                {
                    if (model.Id > 0)
                    {
                        var oldmodel = db.Query<ShopLeaseInfo>().Where(x=>x.Id==model.Id).FirstOrDefault();
                        model.ShopId = oldmodel.ShopId;
                        model.ShopState = oldmodel.ShopState;
                        model.SysUserId = oldmodel.SysUserId;
                        model.AddTime = oldmodel.AddTime;

                        var ShopsInfo= db.Query<ShopsInfo>().Where(x=>x.Id==oldmodel.ShopId).FirstOrDefault();
                        ShopsInfo.ShopAddress = model.ShopAddress;

                        db.Update(ShopsInfo);
                        db.Update(model);
                    }
                    else
                    {
                        ShopsInfo infomodel = new ShopsInfo()
                        {
                            ShopNumber = EncryptionMD5.GetRandomSeed().ToString(),
                            ShopAddress = model.ShopAddress,
                            AddTime = DateTime.Now
                        };
                        int Id = db.Insert(infomodel).Id;
                        model.ShopId = Id;
                        model.AddTime = DateTime.Now;
                        db.Insert(model);
                        db.Session.CommitTransaction();
                    }                    
                    return 1;
                }
                catch
                {
                    if (db.Session.IsInTransaction)
                        db.Session.RollbackTransaction();
                    return 0;
                }
            }
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public List<ShopLeaseInfo> GetList()
        {
            using (var db = ContextHelper.Context(ContextHelper._connString))
            {
                return db.Query<ShopLeaseInfo>().ToList();
            }
        }
    }
}
